package com.lc.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * Author:LiChuang
 * Date: 2022/8/5 16:23
 */
@Slf4j
@Component
public class TokenCheckFilter implements GlobalFilter, Ordered {

    private final List<String> ALLOW_URL = Arrays.asList("/doLogin", "/MyURL", "/login-server/doLogin");

    private final static Logger LOG = LoggerFactory.getLogger(TokenCheckFilter.class);

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        LOG.info("当前访问路径->>>>>>>>>>>>>>>>>>>>>：" + path);
        //判断是否为初次登录
        if(ALLOW_URL.contains(path)){
            return chain.filter(exchange);
        }
        //不为第一次登录，校验token
        List<String> authorizations = request.getHeaders().get("Authorization");
        if(!CollectionUtils.isEmpty(authorizations)){
            String token = authorizations.get(0);
            if(StringUtils.hasText(token)){
                //因为token有一个前缀"bearer "，需要把它去掉
                String realToken = token.replaceAll("bearer ", "");
                if(StringUtils.hasText(realToken) && redisTemplate.hasKey(realToken)){
                    return chain.filter(exchange);
                }
            }
        }
        //无token进行拦截
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().set("content-type", "application/json;charset=utf-8");
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        map.put("msg", "用户未授权");
        //因该方法的返回值类型为Mono，以下代码对返回值进行封装成Mono
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = new byte[0];
        try {
            bytes = objectMapper.writeValueAsBytes(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        DataBuffer wrap = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
